package miniP;
import java.io.Reader;
import java.io.StringReader;

import parser.MiniP;
import parser.MiniPConstants;
import parser.Token;
public class Parser implements MiniPConstants {
    	MiniP scanner;
	Token tok;
	<scanner> void accept(int t) throws ParseException{
		if(tok.kind == t)
			tok = scanner.getNextToken();
		else
			error("parsing error, wanted " + tokenImage[t] + ", got " + tokenImage[tok.kind]);
	}
	void error(String err) throws ParseException{
		throw new ParseException(err);
	}
	public Parser(String s){
		Reader reader = new StringReader(s);
		scanner = new MiniP(reader);
		tok = scanner.getNextToken();
	}
	public void program() throws ParseException{
		stmt();
	}
	void stmt() throws ParseException{
		switch(tok.kind){
			case FOR:
				forStmt();
				break;
			case IF:
				ifStmt();
				break;
			case ID:
				assignment();
				break;
			default:
				error("wanted FOR|IF|ID");
				break;
			
		}
	}
	void forStmt() throws ParseException{
		accept(FOR);
		accept(ID);
		accept(ASSIGN);
		expr();
		accept(UNTIL);
		expr();
		accept(DO);
		stmt();
		accept(OD);
	}
	void ifStmt() throws ParseException{
		accept(IF);
		expr();
		accept(THEN);
		stmt();
		accept(FI);
		
		
	}
	void assignment() throws ParseException{
		accept(ID);
		accept(ASSIGN);
		expr();
	}
	void expr() throws ParseException{
		switch(tok.kind){
		case ID:
			accept(ID);
			break;
		case NUMERAL:
			accept(NUMERAL);
			break;
		default:
			error("wanted ID|NUM|NOT");
			break;
		}
	}

	public class ParseException extends Exception {
		public ParseException(String message) {
			super(message);
		}
	}
}
